package com.kennedy.springbootjpa.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件上传Util
 */
public class FileUploadUtil {
    public static FileResponse uploadFile(MultipartFile multipartFile, String path) {
        if (!new File(path).exists()) {
            new File(path).mkdirs();
        }
        FileResponse fileResponse = new FileResponse();
        String fileName = multipartFile.getOriginalFilename().substring(0, multipartFile.getOriginalFilename().lastIndexOf("."));
        fileResponse.setFileName(fileName);
        String newFileName = fileName + "_" + System.currentTimeMillis() + multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        fileResponse.setNewFileName(newFileName);
        File file = new File(path + "\\" + newFileName);
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return fileResponse;
    }

    public static class FileResponse {
        private String fileName;
        private String newFileName;

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public String getNewFileName() {
            return newFileName;
        }

        public void setNewFileName(String newFileName) {
            this.newFileName = newFileName;
        }
    }
}
